<?php
require_once($common_data_server.'modules/shop/shop.php'); 

/** Корзина покупателя
 * @author  Холодий Андрей
 * @version 1.1
 * @copyright Copyright 2003, РБК СОФТ
 * @package E-shop
 * @subpackage basket
 */

class basket extends shop {

  /**Инициализация модуля
   * @return mixed
   */
  function content_init() { 	
	global $common_data_server;

	if (!$this -> templateInit("{$common_data_server}module_templates/basket/{$this -> view_param['template']}/{$this -> view_param['view_mode']}.vtmpl")) return false;

	$this -> currencyInit();
	$this -> checkQParam();

	session_start();
  $session_name=session_name();
	if ($_COOKIE[$session_name]){
			setcookie($session_name,$_COOKIE[$session_name],time()+60*60*24,'/');
	}

	if (!$_SESSION['cart']) $_SESSION['cart'] = new cart;

    if ($this -> isRegistratedClient() && !$_SESSION['is_synchronized']) $this -> synchronizeBasket();

	
	if (is_numeric($this -> q_param['in_id']) || 
		is_numeric($this -> q_param['wait_id'])) {

	    if (count($_SESSION['cart'] -> items) > 0) {

	    	// Проверяет существования 
	    	foreach ($_SESSION['cart'] -> items as $item)
	    
	    		if ($item['id'] == $this -> q_param['in_id'] ||
	    			$item['id'] == $this -> q_param['wait_id']) $flag = true;
	    } 

	    if (!$flag) 
        	// Добавление товара в корзину
	    	$this -> addItem();
	    else
			// Изменение статуса товара (в корзине или отложенный)
			foreach ($_SESSION['cart'] -> items as $item)
				
				if ($item['id'] == $this -> q_param['wait_id'] &&
					!$item['status']) 	
					$this -> changeStatusItem($this -> q_param['wait_id'], 1);
				
				elseif ($item['id'] == $this -> q_param['in_id'] &&
					 $item['status']) 	
					 $this -> changeStatusItem($this -> q_param['in_id'], 0);
			
	}

	// Удаление товара из корзины
	if (is_numeric($_GET["del_id"])) $this -> removeItem($_GET["del_id"]);	

	// Вариант использования "Статус корзины"
	if ($this -> view_param['view_mode'] == 'status') {
		
		$this -> tmpl -> setVar('_url', 		 $this -> go_to_page($this -> view_param["go_to_page"]));
		$this -> tmpl -> setVar('_product_in', 	 $_SESSION['cart'] -> countItems(0));
		$this -> tmpl -> setVar('_product_wait', $_SESSION['cart'] -> countItems(1));

	// Вариант использования "Товары в корзине"
	} elseif ($this -> view_param['view_mode'] == "product_in" && 
			  $_SESSION['cart'] -> countItems(0)) 	$this -> modeProductIn();

	// Вариант использования "Отложенные товары"
	elseif ($this -> view_param['view_mode'] == "product_wait" && 
			$_SESSION['cart'] -> countItems(1)) 	$this -> modeProductWait();

	$this -> tmpl -> setVar('TAREA', $this -> tarea_id);
	
    $this -> body = $this -> tmpl->grab();
  }

  /***************************** Вариант использования "Отложенные товары" *******************/
  function modeProductWait() {
  	
	// Сохранение комментариев пользователя
	foreach ($_SESSION['cart'] -> items as $item)
		if ($this -> q_param[$item['id']."_comment"] && $item['status']) {
			 $this -> saveComments();
			 break;
		}

  	$product_arr = array();
  	$i = 0; 
  	foreach ($_SESSION['cart'] -> items as $item) 
  		if ($item['status']) {
  			$product_ = sql_select("select * from PRODUCT where CONTENT_ID = ".intval($item['id'])." and LANG_ID = ".intval($this -> lang_id)." and VERSION = ".intval($this -> version));
			//Если товар был удален, пока черепашливый юзер выбирал товары
  			if (!count($product_)) {
  				$_SESSION['cart'] -> removeItem($item['id']); 
  				break;
  			}
  			foreach ($product_ as $product) 
	  			$product["_i"] = ++$i;
	  		$product["_productUrl"] = $this -> getProductUrl($item['id']);
	  		$product["_comment"] = $item['comments'];
  			$product["PRICE"] = $this -> getPrice($product['PRICE']);
  			$product["_del_url"] = make_query_string(array("del_id" => $product["CONTENT_ID"], 'in_id' => "", 'wait_id' => ""));
  			$product["_wait_url"] = make_query_string(array("del_id" => "", 'in_id' => $product["CONTENT_ID"], 'wait_id' => ""));
  			$product_arr[] = $product;
  		}  	
  	$this -> tmpl->setLoop("_product_loop", $product_arr);
  	$this -> tmpl->setVar("_publishedCurrency", $this -> publishedCurrency['NAME_SHORT']);
  }


  /***************************** Вариант использования "Товары в корзине" *******************/
  function modeProductIn() {
  	
	// Пересчет товара в корзине
	foreach ($_SESSION['cart'] -> items as $item)
		if (is_numeric($this -> q_param[$item['id']."_quantity"]) && !$item['status']) {
			 $this -> toCountItem();
			 break;
		}

  	$product_arr = array();
  	$i = 0; 
  	foreach ($_SESSION['cart'] -> items as $item) 
  		if (!$item['status']) {
  			$product_ = sql_select("select * from PRODUCT where CONTENT_ID = ".intval($item['id'])." and LANG_ID = ".intval($this -> lang_id)." and VERSION = ".intval($this -> version));
			//Если товар был удален, пока черепашливый юзер выбирал товары
  			if (!count($product_)) {
  				$_SESSION['cart'] -> removeItem($item['id']); 
  				break;
  			}
  			foreach ($product_ as $product) 
	  			$product["_i"] = ++$i;
	  		$product["_productUrl"] = $this -> getProductUrl($item['id']);
  			$product["_quantity"] = $item['quantity'];
  			$full_cost += ((int)$item['quantity'])*$product["PRICE"];
  			$product['_cost'] = $this -> getPrice(((int)$item['quantity'])*$product['PRICE']);
  			$product['PRICE'] = $this -> getPrice($product['PRICE']);
  			$product["_del_url"] = make_query_string(array("del_id" => $product["CONTENT_ID"], 'wait_id' => "", 'in_id' => ""));
  			$product["_wait_url"] = make_query_string(array("del_id" => "", 'wait_id' => $product["CONTENT_ID"], 'in_id' => ""));
  			$product_arr[] = $product;
  		}  	
  	$this -> tmpl->setLoop("_product_loop", $product_arr);
  	$this -> tmpl->setVar("_full_cost", $this -> getPrice($full_cost));
	$this -> tmpl->setVar("_full_costMain", $this -> getPrice($full_cost, 'main'));
	$this -> tmpl->setVar("_mainCurrency", $this -> mainCurrency['NAME_SHORT']);
  	$this -> tmpl->setVar("_publishedCurrency", $this -> publishedCurrency['NAME_SHORT']);
  	$this -> tmpl->setVar("_urlForOrder", $this -> getUrlForModule('orders'));  	
  }

  /***************************** saveComment *******************/
  function saveComments() {
  /*
	Сохранение комментариев пользователя.
	Синхронизация с БД, если пользователь авторизован.
  */
	for ($i = 0; $i < count($_SESSION['cart'] -> items); $i++) {
		
		$key = "{$_SESSION['cart'] -> items[$i]['id']}_comment";
		if (isset($this -> q_param[$key]) && $_SESSION['cart'] -> items[$i]['status']) {

			$_SESSION['cart'] -> items[$i]['comments'] = $this -> q_param[$key];
			
			// Синхронизация с БД
			if ($this -> isRegistratedClient()) {
				
				$basket_id = 
					sql_select("select * from BASKET 
								where 
									CLIENT_ID  = ".intval($_COOKIE['client_id'])." and 
									CONTENT_ID = ".intval($_SESSION['cart'] -> items[$i]['id']));
				
				update_record('BASKET', array( array(
						'name' 	=> 'COMMENTS', 
						'value' => $_SESSION['cart'] -> items[$i]['comments']
					)), 
					'BASKET_ID', 
					$basket_id[0]['BASKET_ID']
				);
			}
		}
	}
  }

  /***************************** toCountItem *******************/
  function toCountItem() {
  /*
	Пересчет количества товара в корзине. 
	Синхронизация с БД, если пользователь авторизован.
  */				

	for ($i = 0; $i < count($_SESSION['cart'] -> items); $i++) {
		
		$key = "{$_SESSION['cart'] -> items[$i]['id']}_quantity";

		if ($this -> q_param[$key] > 0 && !$_SESSION['cart'] -> items[$i]['status']) {
			$_SESSION['cart'] -> items[$i]['quantity'] = intval($this -> q_param[$key]);

			/*if ($this -> isRegistratedClient()) {
				$basket_id = sql_select('select * from BASKET where CLIENT_ID = '.intval($_COOKIE['client_id'])." and CONTENT_ID = ".intval($_SESSION['cart'] -> items[$i]['id']));
				update_record('BASKET', array(
					array('name' => 'QUANTITY', 'value' => $_SESSION['cart'] -> items[$i]['quantity'])
					), 'BASKET_ID', $basket_id[0]['BASKET_ID']);
			}*/
		}
	}
  }

  /***************************** changeStatusItem *******************/
  function changeStatusItem($id,		 // content_id товара в БД
  							 $status) { // статус товара
  /*
	Изменение статуса товара. 
	Синхронизация с БД, если пользователь авторизован.
  */				

	$_SESSION['cart'] -> changeStatusItem($id, $status); 

	if (!$this -> isRegistratedClient()) return false;
	
	foreach ($_SESSION['cart'] -> items as $item)
		if ($item['id'] == $id)
			if ($status)
				insert_record('BASKET', array(
					array('name' => 'CLIENT_ID', 'value' => intval($_COOKIE['client_id'])),
					array('name' => 'CONTENT_ID', 'value' => intval($item['id'])),
					array('name' => 'QUANTITY', 'value' => $item['quantity']),
					array('name' => 'STATUS', 'value' => $status),
					array('name' => 'COMMENTS', 'value' => htmlspecialchars($item['comments'], ENT_QUOTES))
				));
			else 
				delete_record2('BASKET', array(
						array(name => 'CLIENT_ID', value => intval($_COOKIE['client_id'])),
						array(name => 'CONTENT_ID', value => intval($id))));
  }

  /***************************** removeItem *******************/
  function removeItem($id) {
  /*
	Удаление товара из корзины. 
	Синхронизация с БД, если пользователь авторизован.
  */				
	
	$_SESSION['cart'] -> removeItem($id); 

	if (!$this -> isRegistratedClient()) return false;
	
	delete_record2('BASKET', array(
			array(name => 'CLIENT_ID', value => intval($_COOKIE['client_id'])),
			array(name => 'CONTENT_ID', value => intval($id))));
  }

  /***************************** addItem *******************/
  function addItem() {
  /*
	Добавление товара в корзину покупателя. 
	Синхронизация с БД, если пользователь авторизован.
  */				
  	
  	$productID 	= ($this -> q_param['in_id'] ? $this -> q_param['in_id'] : $this -> q_param['wait_id']);
  	$status		= ($this -> q_param['in_id'] ? 0 : 1);
  	$quantity	= 1;
  	
	
	if (!count(sql_select("select * from PRODUCT where CONTENT_ID = '".intval($productID)."' and 
						  LANG_ID = ".intval($this -> lang_id)." and VERSION = ".intval($this -> version)))) return false;
	
	$_SESSION['cart'] -> addItem($productID, $quantity, $status); 
	
	if (!$this -> isRegistratedClient() || 
		count(sql_select("select * from BASKET 
						  where 
						  		CLIENT_ID = ".intval($_COOKIE['client_id'])." and 
						  		CONTENT_ID = ".intval($productID)))) return false;
	
	if ($this -> q_param['wait_id'])
		insert_record('BASKET', array(
			array('name' => 'CLIENT_ID', 	'value' => intval($_COOKIE['client_id'])),
			array('name' => 'CONTENT_ID',	'value' => intval($productID)),
			array('name' => 'QUANTITY',		'value' => $quantity),
			array('name' => 'STATUS', 		'value' => $status),
			array('name' => 'COMMENTS', 	'value' => '')
		));
  } 
  
  /***************************** synchronyzeBasket *******************/
  function synchronizeBasket() {
  /*
	Синхронизация с БД.
  */				
	$_SESSION['is_synchronized'] = 1;

	$items_arr = sql_select("select * from BASKET where CLIENT_ID = ".intval($_COOKIE["client_id"]));
	
	if (!count($items_arr) && !count($_SESSION['cart'] -> items)) return false;

	//Наложение (БД -> сессия)
	if (count($items_arr) && count($_SESSION['cart'] -> items)) {

		foreach ($items_arr as $item) {

			foreach ($_SESSION['cart'] -> items as $cart_item)
				if ($item['STATUS'] == 1 && $item['CONTENT_ID'] == $cart_item['id']) $is_product = true;
			
			if (!$is_product)
				$_SESSION['cart'] -> addItem($item['CONTENT_ID'], $item['QUANTITY'], 1, $item['COMMENTS']); 
			else $is_product = false;
		}
	}
	
	//Добавление 
	if (count($items_arr) && !count($_SESSION['cart'] -> items))
		foreach ($items_arr as $item)
				if ($item['STATUS'] == 1)
					$_SESSION['cart'] -> addItem($item['CONTENT_ID'], $item['QUANTITY'], 1, $item['COMMENTS']); 

	delete_record('BASKET', 'CLIENT_ID', intval($_COOKIE['client_id']));
/*	//Наложение (Сессия -> БД)
	foreach ($_SESSION['cart'] -> items as $cart_item) {

		foreach ($items_arr as $item)
			if ($item['STATUS'] == 1 && $item['CONTENT_ID'] == $cart_item['id']) $is_product = true;
		
		if (!$is_product)
			insert_record('BASKET', array(
				array('name' => 'CLIENT_ID', 'value' => $_COOKIE['client_id']),
				array('name' => 'CONTENT_ID', 'value' => $item['id']),
				array('name' => 'QUANTITY', 'value' => $item['quantity']),
				array('name' => 'STATUS', 'value' => $item['status']),
				array('name' => 'COMMENTS', 'value' => htmlspecialchars($item['comments'], ENT_QUOTES))
			));
		else $is_product = false;
	}*/

	foreach ($_SESSION['cart'] -> items as $item)
		if ($item['status'])
			insert_record('BASKET', array(
				array('name' => 'CLIENT_ID', 'value' => intval($_COOKIE['client_id'])),
				array('name' => 'CONTENT_ID', 'value' => intval($item['id'])),
				array('name' => 'QUANTITY', 'value' => $item['quantity']),
				array('name' => 'STATUS', 'value' => $item['status']),
				array('name' => 'COMMENTS', 'value' => htmlspecialchars($item['comments'], ENT_QUOTES))
			));
  }

  /**
   * Инициализация шаблона
   * @return boolean
   */
  function templateInit($templateFile) {
  	
    if (!file_exists($templateFile)) {

	   		$this -> body = "Шаблон отсутствует: $templateFile";
	   		return false;
	}

    $this -> tmpl = new vlibTemplate();
    $this -> tmpl -> newTemplate($templateFile);
    
    return true;
  }

  /**Инициализация валют
   * @return mixed
   */
  function currencyInit() {
  	
    $this -> publishedCurrency 	= $this -> getPublishedCurrency();
    $this -> mainCurrency 		= $this -> getMainCurrency();
  }

  /**Проверяются входные данные из q_param и GET
   * @return mixed
   */
  function checkQParam() {
  	
	if (is_numeric($_GET['wait_id']) && 
		!is_numeric($this -> q_param['wait_id'])) 	$this -> q_param['wait_id'] = $_GET['wait_id'];
	
	if (is_numeric($_GET['in_id']) && 
		!is_numeric($this -> q_param['in_id'])) 	$this -> q_param['in_id'] = $_GET['in_id'];
		
	if (!is_numeric($this -> q_param['in_id']))		$this -> q_param['in_id'] = 0;
	if (!is_numeric($this -> q_param['wait_id']))	$this -> q_param['wait_id'] = 0;
  }

  /**Отключается кэширование модуля
   * @return boolean
   */
  function get_hash_code() {return false;}
  
}
?>